<template>
	<view class="mian">
		<view class="bg-set"></view>
		<!-- 有订单 -->

		<scroll-view scroll-y="true" style="height: 98vh;" v-if="orderList.length > 0" @scrolltolower="fn">
			<uni-card padding="10px 0" v-for="(item, index) in orderList" :key="index" margin="10">
				<template v-slot:title>
					<view class="header">
						<view class="del_box">
							<view class="delivery">配送</view>
							<view>{{ item.orderCategoryName }}<text style='color:#2979ff'>{{ '(' + item.orderDate + ')'
							}}</text>
							</view>
							<!-- <view class="time">
                <view> 配送 </view>
                <uni-countdown :show-day="false" :hour="12" :minute="12" :second="12" color="#007AFF" />
              </view> -->
						</view>

						<view style="font-weight: 700;">{{ item.orderStatusName }}</view>
					</view>
				</template>
				<view class="content">
					<view style="display: flex;">
						<image
							:src="item.foodlist?.length > 0 && item.foodlist[0].imgPath || item.foodPackagelist?.length > 0 && item.foodPackagelist[0].imgPath ? ('https://api.victorick.com:8222/' + item.foodlist[0].imgPath) || ('https://api.victorick.com:8222/' + item.foodPackagelist[0].imgPath) : 'https://bpic.51yuansu.com/pic3/cover/02/00/33/5984a86e2f6f5_610.jpg'"
							class="img" />
						<view v-if="item.foodlist?.length > 0">
							<text style="margin-left: 20rpx;" v-for="(it, index) in item.foodlist" :key="index">
								{{ it.foodName }}x{{ it.number }}
							</text>
						</view>
						<view v-if="item.foodpackagelist?.length > 0">
							<view v-for="(i, index) in item.foodpackagelist" :key="index">
								<view>{{ i.foodPackageName }}x{{ i.number }}</view>
								<view v-for="(t, index) in i.foodlist" :key="index">【{{ t.foodName }}x{{ t.number }}】
								</view>
							</view>
						</view>
					</view>
					<view class="right">
						<view style="color: black;"> ￥{{ item.totalAmount }}</view>
						<view>共{{ item.sum }}件</view>
					</view>
				</view>
				<view class="footer">
					<view>配送地址：<text>{{ storeUser.profile?.addressTxt }}</text></view>
					<view>订单编号：<text>{{ item.orderNo }}</text></view>
					<!-- <view>预计配送：<text>2023-06-06 11：00-12：00</text></view> -->
					<view>下单时间：<text @click="reFoundBtn(item)">{{ item.createTime }}</text></view>
				</view>
				<!--  -->
				<view class="btn" v-if="item.orderStatusCode == 2">
					<view class="btn_apply" v-if="suan(item)">退款请联系管理员</view>
					<view class="btn_pay" v-else @click="reFoundBtn(item)">
						申请退款</view>
				</view>
			</uni-card>
		</scroll-view>

		<!-- 无订单 -->
		<view v-else class="box">
			暂未有数据
		</view>
	</view>
</template>

<script setup>
// import global from '../../utils/websokect.js'//--------------------hsq修改
import { timeToTimestamp, timestampToTime } from '../../utils/data'
import {
	ref,
	nextTick
} from "vue";
import {
	onShow
} from '@dcloudio/uni-app';
import {
	useMemberStore,
	useCartStore,
	useTimeStore
} from "../../stores";
import {
	http
} from "../../utils/http";
const storeUser = useMemberStore()
const storeCart = useCartStore()
let endTime = ref('')
const orderDataList = ref([])
const orderList = ref([])
const restime2 = ref()
onShow(() => {
	getFoodOrders()
	getRestaurant()
})

//在规定时间内是否允许小程序退款
const suan = (item) => {

	const createTime = item.createTime.split(' ')[0]//订单创建时间
	const sysRestime = restime2.value.split(' ')[0].split("/");
	const formattedDate = `${sysRestime[0]}-${sysRestime[1].padStart(2, "0")}-${sysRestime[2].padStart(2, "0")}`;//当前时间
	if (endTime.value) {
		const time = timeToTimestamp(endTime.value) - timeToTimestamp(restime2.value)
		// 退款时间 判断当前日期下，获取订单返回的时间和订单创建时间对比，超过一定时间不允许用户在手机端退款
		if (createTime == formattedDate && time > 0) {
			return false
		} else {
			return true
		}
	}

}
// 获取餐厅营业时间
const getRestaurant = async () => {
    const res = await http({
        url: '/GetRestaurant',
        method: 'post',
        data: storeUser.requestData
    })
    endTime.value=res.restime.split(' ')[0]+' '+res.data[0].endTime
}
// 获取订单
const getFoodOrders = async () => {
	// console.log(storeUser.requestData);
	// debugger
	// orderCategory.value = storeCart.cart.forEach(item => orderCategory.value.push(item.orderCategoryName))
	// 获取所有的订单详情
	const {
		restime,
		data
	} = await http({
		url: '/GetFoodOrders',
		method: 'post',
		data: {
			...storeUser.requestData,
			data: {
				"orderNo": [
					""
				],
				"addressSerials": [

				],
				"addressId": [

				],
				"addressName": '',
				"orderStatusCode": [

				],
				"orderCategorySerials": [],
				"restaurantSerials": [

				],
				"restaurantName": '',
				"createBeginTime": "",
				"createEndTime": ""
			}
		}
	})
	restime2.value = restime
	orderDataList.value = data
	const result = orderDataList.value && orderDataList.value.length > 0 ? orderDataList.value.map(({
		createTime,
		foodlist,
		foodpackagelist,
		notes,
		orderCategoryName,
		orderDate,
		orderNo,
		orderStatusCode,
		orderStatusName,
		totalAmount,
		payinfolist,
		orderSerials
	}) => ({
		createTime,
		notes,
		orderCategoryName,
		orderNo,
		orderStatusCode,
		orderStatusName,
		totalAmount,
		payinfolist,
		orderSerials,
		orderDate,
		foodlist: foodlist ? foodlist.map(({
			foodName,
			number,
			imgPath
		}) => ({
			foodName,
			number,
			imgPath
		})) : [],
		foodpackagelist: foodpackagelist ? foodpackagelist.map(({
			foodPackageName,
			number,
			foodlist,
			imgPath
		}) => ({
			foodPackageName,
			number,
			imgPath,
			foodlist: foodlist ? foodlist.map(({
				foodName,
				number
			}) => ({
				foodName,
				number
			})) : []
		})) : []
	})) : []
	result.forEach(item => {
		let sum = 0
		if (Array.isArray(item.foodpackagelist) && item.foodpackagelist?.length > 0) {
			item.foodpackagelist.forEach(n => sum += Number(n.number))
		}
		if (Array.isArray(item.foodlist) && item.foodlist?.length > 0) {
			item.foodlist.forEach(n => sum += Number(n.number))
		}
		item.sum = sum
	})
	orderList.value = result

}
// 取消订单
const cancelFoodOrders = async (orderSerials, payinfolist, orderNo) => {
	const res = await http({
		method: 'post',
		url: '/CancelFoodOrders',
		data: {
			...storeUser.requestData,
			data: {
				foodorderlist: [{
					orderSerials
				}]
			}
		}
	})
	if (res.errcode == '0') {
		if (payinfolist != null && payinfolist[0].payWay == 'WX') {
			const arr = Object.values(payinfolist)[0];
			const {
				payNo,
				payWay: payWayCode,
				paymentAmount
			} = arr
			const obj = {
				orderNo,
				payNo,
				paymentAmount,
				payWayCode: 'WX',
				payWayName: '微信支付',
			}
			cancelPayForOrder(obj) //退款
		} else {
			const message = {
				ReqType: 'orderprint',
				ReqUser: storeUser.profile?.openId, //患者id
				ReqData: orderNo, //消息内容
				CheckData: storeUser.profile?.openId,
				RcvUsers: ['wx']
			};
			// global.ws.send({
			// 	data: JSON.stringify(message)
			// });//--------------------hsq修改
			uni.showToast({
				title: '操作成功',
				icon: 'none'
			})
			getFoodOrders()
			GetCustomersInfo()
		}
	} else {
		uni.showToast({
			title: res.resmsg,
			icon: "none",
			duration: 1500,
		});
	}
	//重新刷新页面更新状态
	console.log(res, '退款');
}
//订单取消退款
const cancelPayForOrder = async (e) => {
	const res = await http({
		method: 'post',
		url: '/CancelPayForOrder',
		data: {
			...storeUser.requestData,
			data: {
				...e
			}
		}
	})
	if (res.errcode == '0') {
		const message = {
			ReqType: 'orderprint',
			ReqUser: storeUser.profile?.openId, //患者id
			ReqData: e.orderNo, //消息内容
			CheckData: storeUser.profile?.openId,
			RcvUsers: ['wx']
		};
		// global.ws.send({
		// 	data: JSON.stringify(message)
		// });//--------------------hsq修改
		uni.showToast({
			title: '退款成功',
			icon: 'none'
		})
		getFoodOrders() //重新获取订单
		GetCustomersInfo() //重新获取用户退款后的余额，餐补
	} else {
		uni.showToast({
			title: res.resmsg,
			icon: "none",
			duration: 1500,
		});
		getFoodOrders()//不再等退款流程走完，重新获取订单刷新页面状态
	}

}
// 点击退款
const reFoundBtn = (item) => {

	// const obj = {
	// 	orderNo:item.orderNo,
	// 	payNo: item.payinfolist[0].payNo,
	// 	paymentAmount:item.payinfolist[0].paymentAmount,
	// 	payWayCode: 'WX',
	// 	payWayName: '微信支付'
	// }
	// console.log(obj);
	// debugger
	// cancelPayForOrder(obj) //退款

	// return
	// 赠送订单
	let zero = []
	if (item.payinfolist != null) {
		zero = orderDataList.value.filter(row => row.orderDate == item.orderDate && row.payinfolist == null && row.orderStatusCode != 7)
		if (zero.length > 0) {
			uni.showModal({
				title: '确定要申请退款吗？',
				content: '该操作将取消当天所有订单',
				success: (res) => {
					if (res.confirm) {
						zero.forEach(async row => {
							const res = await http({
								method: 'post',
								url: '/CancelFoodOrders',
								data: {
									...storeUser.requestData,
									data: {
										foodorderlist: [{
											orderSerials: row.orderSerials
										}]
									}
								}
							})
						})
						nextTick(() => {
							cancelFoodOrders(item.orderSerials, item.payinfolist, item.orderNo)
						})
						console.log('用户点击确定');

					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			})
		} else {
			console.log(zero, 'zero');
			uni.showModal({
				title: '确定要申请退款吗？',
				content: '退款金额将在1~7工作日返回账号',
				success: (res) => {
					if (res.confirm) {
						cancelFoodOrders(item.orderSerials, item.payinfolist, item.orderNo)
						console.log('用户点击确定');

					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			})
		}
	} else {
		uni.showModal({
			title: '请确认是否取消订单？',
			success: (res) => {
				if (res.confirm) {
					cancelFoodOrders(item.orderSerials, item.payinfolist, item.orderNo)
					console.log('用户点击确定');

				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		})
	}



}
//重新获取用户信息
const GetCustomersInfo = async () => {
	const store = useMemberStore()
	const res = await http({
		method: 'post',
		url: '/GetCustomersInfo',
		data: store.requestData
	})
	store.profile = {
		...store.profile,
		...res.data[0]
	}
}
</script>

<style scoped lang="scss">
.bg-set {
	position: fixed;
	width: 100%;
	height: 100%;
	top: 0;
	left: 0;
	background-color: #c2e2f5;
	z-index: -1;
}

.main {
	padding: 20rpx;

}

.header {
	display: flex;
	justify-content: space-between;
	height: 100rpx;
	border-bottom: 2rpx dotted #a9d1eb;
	align-items: center;

	.del_box {
		display: flex;
		align-items: center;

		.time {
			display: flex;
			font-size: 25rpx;
			align-items: center;
			margin-left: 20rpx;

		}

		.delivery {
			width: 100rpx;
			height: 50rpx;
			text-align: center;
			line-height: 50rpx;
			border-radius: 12rpx;
			margin-right: 15rpx;
			color: #fff;
			background-color: #2979ff;
		}

	}

}

.content {
	display: flex;
	justify-content: space-between;
	align-items: center;
	border-bottom: 2rpx solid #eee;
	padding-bottom: 20rpx;

	.img {
		width: 100rpx;
		height: 100rpx;
		border-radius: 12rpx;
		margin-right: 20rpx;
	}

	.right {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
}

.footer {
	display: flex;
	flex-direction: column;
	justify-content: space-evenly;
	height: 230rpx;
	margin-top: 20rpx;

	text {
		color: black;
	}
}

.box {
	text-align: center;
	margin: 20rpx auto;

}

.btn {
	width: 100%;
	display: flex;
	justify-content: flex-end;

	.btn_cancel,
	.btn_pay {
		width: 150rpx;
		height: 50rpx;
		text-align: center;
		line-height: 50rpx;
		margin-left: 20rpx;
		border: 2rpx solid #2979ff;
		border-radius: 12rpx;
		background-color: #fff;
		color: #2979ff;
	}

	.btn_apply {
		color: red;
	}

	.btn_cancel {
		background-color: #efefef;
		color: black;
	}
}
</style>